﻿using UnityEngine;
using System.Collections;
using com.gzc.zgxq.game;
using System;

/// <summary>
/// 棋盘数据模型
/// </summary>
public class ChessBoardModel {

    public class PointModel {
        public int Index256 { get; private set; }
        public WhichChess whichChess;

        public PointModel (int row, int column) {
            Index256 = ToIndex256(row, column);
        }

        private int ToIndex256 (int row, int column) {
            // 二维数组 a[INDEX1][INDEX2] 转换成一维数组b[INDEX1*INDEX2]，则a[i][j] 对应一维数组的索引 b[INDEX2*i+j]
            // 只与列数有关，与行数无关。
            int index256 = 16 * row + column;
            return index256;
        }
    }

    private PointModel[,] m_points;
    private byte[ ] m_chessBordArr;

    public PointModel[,] Points {
        get {
            return m_points;
        }
    }

    public ChessBoardModel ( ) {
        Create( );
        InitChessBord( );
        InitPoints( );
    }

    void Create ( ) {
        m_points = new PointModel[10, 9];
        m_chessBordArr = new byte[256];
    }

    public void TraverseChessBord (Action<int> action) {
        for (int i = 0; i < 256; i++) {            
            Util.CallAction(action, i);
        }
    }

    public void TraversePoints (Action<int, int> action) {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 9; j++) {
                Util.CallAction(action, i, j);
            }
        }
    }

    public void InitChessBord ( ) {       
        TraverseChessBord((i) => {
            m_chessBordArr[i] = GameConstant.INIT_CHESS_BORD[i];
        });
    }

    public void InitPoints ( ) {
        TraversePoints((row, col) => {
            m_points[row, col] = new PointModel( row,col);           
            AddPiece(row, col, (WhichChess)GameConstant.INIT_CHESS_BORD[m_points[row, col].Index256]);
        });
    }

    /// <summary>
    /// 在棋盘上放一枚棋子，当加一枚棋子时，要将加的该棋子对应该位子的子力价值从该方在该局下的局面价值上加
    /// </summary>
    /// <param name="index256">位置下标</param>
    /// <param name="whichChess">哪颗棋子代号</param>
    public void AddPiece (int i, int j, WhichChess whichChess) {        
        m_points[i, j].whichChess = whichChess;
        AddDataPiece(i, j);
    }

    private void AddDataPiece (int i, int j) {
        m_chessBordArr[m_points[i, j].Index256] = (byte)m_points[i, j].whichChess;
    }

    /// <summary>
    /// 从棋盘上拿走一枚棋子，当拿走一枚棋子时，要将拿走的该棋子对应该位子的子力价值从该方在该局下的局面价值上减去
    /// </summary>
    /// <param name="index256">位置下标</param>
    /// <param name="whichChess">哪颗棋子</param>
    public void DelPiece (int i,int j) {
        m_points[i, j].whichChess = WhichChess.NONE;
        DelDataPiece(i, j);
    }

    private void DelDataPiece (int i, int j) {
        m_chessBordArr[m_points[i, j].Index256] = (byte)WhichChess.NONE;
    }

}
